const express = require('express');
const fs = require('fs').promises;
const path = require('path');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 3001;

app.use(express.json());
app.use(cors());

const todosPath = path.join(__dirname, 'src', 'data', 'todos.json');

// 获取所有待办事项
app.get('/api/todos', async (req, res) => {
  try {
    const data = await fs.readFile(todosPath, 'utf8');
    res.json(JSON.parse(data));
  } catch (error) {
    if (error.code === 'ENOENT') {
      // 如果文件不存在，创建一个空的待办事项列表
      await fs.writeFile(todosPath, JSON.stringify({ todos: [] }));
      res.json({ todos: [] });
    } else {
      res.status(500).json({ error: '读取数据失败' });
    }
  }
});

// 保存待办事项
app.put('/api/todos', async (req, res) => {
  try {
    const { todos } = req.body;
    await fs.writeFile(todosPath, JSON.stringify({ todos }, null, 2));
    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: '保存数据失败' });
  }
});

app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
}); 